import datetime
import random
from datetime import timedelta
import pytz
import conf

def adjust_time(m_time):
    # 将毫秒级时间戳转换为秒级时间戳
    m_time_seconds = m_time / 1000
    
    # 转换为datetime对象（东八区时间）
    shanghai_tz = pytz.timezone('Asia/Shanghai')
    dt_shanghai = datetime.datetime.fromtimestamp(m_time_seconds, shanghai_tz)
    
    # 检查是否是周末（周六或周日），如需考虑周末不上班的情况，则需要再次修改
    if  conf.is_week and dt_shanghai.weekday() >= 5:  # 5表示周六，6表示周日
        # 计算距离周五的天数（周六减1天，周日减2天）
        days_to_friday = dt_shanghai.weekday() - 4
        friday = dt_shanghai - datetime.timedelta(days=days_to_friday)
        friday = friday.replace(hour=0, minute=0, second=0, microsecond=0)  # 重置为周五0点
        
        # 定义周末时间范围（周六0点到下周一0点）
        saturday_start = friday + datetime.timedelta(days=1)  # 周六0点
        weekend_end = saturday_start + datetime.timedelta(days=2)  # 下周一0点
        
        # 计算当前时间在周末时间范围内的位置（秒数）
        current_second_in_weekend = (dt_shanghai - saturday_start).total_seconds()
        weekend_duration = (weekend_end - saturday_start).total_seconds()  # 2天=172800秒
        
        # 计算百分比（0-1之间），确保在有效范围内
        percentage = current_second_in_weekend / weekend_duration
        percentage = max(0.0, min(1.0, percentage))
        
        # 将百分比映射到周五9点到18点的时间范围（9小时=32400秒）
        friday_9am = friday.replace(hour=9, minute=0, second=0, microsecond=0)
        adjusted_seconds = percentage * 32400  # 9小时的总秒数
        adjusted_dt_shanghai = friday_9am + datetime.timedelta(seconds=adjusted_seconds)
    else:
        # 非周末时间，检查是否在9点到18点之间
        if dt_shanghai.hour < 9 or dt_shanghai.hour >= 18:
            if dt_shanghai.hour < 9:
                hours_from_prev_day = dt_shanghai.hour + 24 - 18
                if hours_from_prev_day >= 9:
                    time_delta = timedelta(days=1)  # 向后移动1天
                    new_hour = hours_from_prev_day
                elif hours_from_prev_day < 9:
                    time_delta = timedelta(days=0)  # 当天
                    new_hour = 9 + hours_from_prev_day
            elif dt_shanghai.hour >= 18:
                time_delta = timedelta(days=1)  # 向后移动1天
                new_hour = dt_shanghai.hour - 18 + 9
            random_minute = random.randint(0, 59)
            random_second = random.randint(0, 59)
            adjusted_dt_shanghai = dt_shanghai + time_delta
            adjusted_dt_shanghai = adjusted_dt_shanghai.replace(hour=new_hour, minute=random_minute, second=random_second)
        else:
            # 已经在工作时间内，无需调整
            adjusted_dt_shanghai = dt_shanghai

    # # 新增逻辑：检查日期是否在5月20日至7月7日之间
    # month = adjusted_dt_shanghai.month
    # day = adjusted_dt_shanghai.day

    # # 判断是否在5月20日到7月7日之间
    # if (month == 5 and day >= 20) or (month == 6) or (month == 7 and day <= 7):
    #     ########################
    #     # 检查是否在6月13号之前
    #     if (month < 6) or (month == 6 and day <= 13):
    #         # 6月13号之前，时间往前挪25天
    #         adjusted_dt_shanghai += timedelta(days=-25)
    #     else:
    #         # 6月14号及之后，时间往后挪25天
    #         if month == 7:
    #             adjusted_dt_shanghai += timedelta(days=7)
    #         else:
    #             adjusted_dt_shanghai += timedelta(days=21)

    # 将调整后的datetime对象转换回毫秒级时间戳
    adjusted_m_time = int(adjusted_dt_shanghai.timestamp() * 1000)
    return adjusted_m_time

def adjust_times(m_time1, m_time2):
    adjusted_m_time1 = adjust_time(m_time1)
    adjusted_dt1 = datetime.datetime.fromtimestamp(adjusted_m_time1 / 1000, pytz.timezone('Asia/Shanghai'))
    
    adjusted_m_time2 = adjust_time(m_time2)
    adjusted_dt2 = datetime.datetime.fromtimestamp(adjusted_m_time2 / 1000, pytz.timezone('Asia/Shanghai'))
    
    # 确保 adjusted_m_time2 大于 adjusted_m_time1
    while adjusted_dt2 <= adjusted_dt1:
        # 如果 adjusted_dt2 不大于 adjusted_dt1，重新生成 adjusted_dt2，可以晚一天
        new_m_time2 = m_time2 + 86400000  # 加一天的毫秒数
        adjusted_m_time2 = adjust_time(new_m_time2)
        adjusted_dt2 = datetime.datetime.fromtimestamp(adjusted_m_time2 / 1000, pytz.timezone('Asia/Shanghai'))
    
    return adjusted_m_time1, adjusted_m_time2


if __name__ == "__main__":
    import pytz
    shanghai_tz = pytz.timezone('Asia/Shanghai')
    
    # 测试用例: (测试名称, 输入时间戳(毫秒))
    test_cases = [
        ("周六正常时间(10:30)", 1717209000000),  # 2024-06-01 10:30:00
        ("周六早上8点", 1717198800000),        # 2024-06-01 08:00:00
        ("周六晚上19点", 1717245600000),       # 2024-06-01 19:00:00
        ("周六0点(周末开始)", 1717257600000),     # 2024-06-01 00:00:00 (周六)
        ("周六中午12点", 1717300800000),         # 2024-06-01 12:00:00 (周六)
        ("周日中午12点", 1752379200000),         # 2024-06-02 12:00:00 (周日)
        ("周日晚上23:59", 1752422340000),       # 2024-06-02 23:59:00 (周日)
        ("极端小时间戳", 1000000000000),          # 2001-09-09 09:46:40
        ("极端大时间戳", 2000000000000)           # 2033-05-18 11:33:20
    ]
    
    print("===== adjust_time 函数测试 =====\n")
    for case_name, input_ms in test_cases:
        # 转换输入时间戳为可读时间
        input_dt = datetime.datetime.fromtimestamp(input_ms/1000, shanghai_tz)
        input_str = input_dt.strftime("%Y-%m-%d %H:%M:%S %A")
        
        # 调用调整函数
        output_ms = adjust_time(input_ms)
        
        # 转换输出时间戳为可读时间
        output_dt = datetime.datetime.fromtimestamp(output_ms/1000, shanghai_tz)
        output_str = output_dt.strftime("%Y-%m-%d %H:%M:%S %A")
        
        # 输出测试结果
        print(f"测试用例: {case_name}")
        print(f"输入时间: {input_str}")
        print(f"输出时间: {output_str}")
        if output_dt.weekday() < 5 and 9 <= output_dt.hour < 18:
            print(f"调整结果: 正常")
        else:
            print(f"调整结果: 不正常")
        print("----------------------------------------")
    
    print("===== 测试完成 =====")
